#!/bin/bash

# =============================================================================
# Nginx配置脚本
# =============================================================================

set -e

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m'

log_info() { echo -e "${BLUE}[INFO]${NC} $1"; }
log_success() { echo -e "${GREEN}[SUCCESS]${NC} $1"; }
log_warning() { echo -e "${YELLOW}[WARNING]${NC} $1"; }
log_error() { echo -e "${RED}[ERROR]${NC} $1"; }

log_info "开始Nginx配置..."

# 获取服务器IP
SERVER_IP=$(curl -s ifconfig.me 2>/dev/null || echo "your_server_ip")

# 询问域名
read -p "请输入域名 (直接回车使用IP: $SERVER_IP): " DOMAIN
if [ -z "$DOMAIN" ]; then
    DOMAIN=$SERVER_IP
fi

log_info "配置域名: $DOMAIN"

# 创建Nginx配置文件
create_nginx_config() {
    log_info "创建Nginx配置文件..."
    
    sudo tee /etc/nginx/sites-available/memebot > /dev/null << EOF
server {
    listen 80;
    server_name $DOMAIN;

    # 安全头
    add_header X-Frame-Options "SAMEORIGIN" always;
    add_header X-XSS-Protection "1; mode=block" always;
    add_header X-Content-Type-Options "nosniff" always;
    add_header Referrer-Policy "no-referrer-when-downgrade" always;
    add_header X-Robots-Tag "noindex, nofollow" always;

    # 限制请求大小
    client_max_body_size 10M;

    # 主应用代理
    location / {
        proxy_pass http://localhost:3000;
        proxy_http_version 1.1;
        proxy_set_header Upgrade \$http_upgrade;
        proxy_set_header Connection 'upgrade';
        proxy_set_header Host \$host;
        proxy_set_header X-Real-IP \$remote_addr;
        proxy_set_header X-Forwarded-For \$proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto \$scheme;
        proxy_cache_bypass \$http_upgrade;
        proxy_read_timeout 86400;
        proxy_connect_timeout 60s;
        proxy_send_timeout 60s;
    }

    # WebSocket代理 (Socket.IO)
    location /socket.io/ {
        proxy_pass http://localhost:3000;
        proxy_http_version 1.1;
        proxy_set_header Upgrade \$http_upgrade;
        proxy_set_header Connection "upgrade";
        proxy_set_header Host \$host;
        proxy_set_header X-Real-IP \$remote_addr;
        proxy_set_header X-Forwarded-For \$proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto \$scheme;
        proxy_read_timeout 86400;
    }

    # 静态文件缓存
    location /_next/static {
        proxy_pass http://localhost:3000;
        add_header Cache-Control "public, max-age=31536000, immutable";
    }

    # 健康检查
    location /health {
        access_log off;
        return 200 "healthy\n";
        add_header Content-Type text/plain;
    }

    # 禁止访问敏感文件
    location ~ /\. {
        deny all;
        access_log off;
        log_not_found off;
    }

    location ~ \.(env|config)$ {
        deny all;
        access_log off;
        log_not_found off;
    }

    # 日志配置
    access_log /var/log/nginx/memebot_access.log;
    error_log /var/log/nginx/memebot_error.log;
}
EOF
    
    log_success "Nginx配置文件创建完成"
}

# 启用站点配置
enable_site() {
    log_info "启用站点配置..."
    
    # 删除默认配置
    sudo rm -f /etc/nginx/sites-enabled/default
    
    # 启用新配置
    sudo ln -sf /etc/nginx/sites-available/memebot /etc/nginx/sites-enabled/
    
    log_success "站点配置已启用"
}

# 测试Nginx配置
test_nginx_config() {
    log_info "测试Nginx配置..."
    
    if sudo nginx -t; then
        log_success "Nginx配置测试通过"
    else
        log_error "Nginx配置测试失败"
        exit 1
    fi
}

# 重启Nginx
restart_nginx() {
    log_info "重启Nginx服务..."
    
    sudo systemctl restart nginx
    sudo systemctl enable nginx
    
    if sudo systemctl is-active --quiet nginx; then
        log_success "Nginx服务启动成功"
    else
        log_error "Nginx服务启动失败"
        sudo systemctl status nginx
        exit 1
    fi
}

# 配置SSL (可选)
setup_ssl() {
    if [ "$DOMAIN" != "$SERVER_IP" ]; then
        read -p "是否配置SSL证书？(y/N): " -n 1 -r
        echo
        if [[ $REPLY =~ ^[Yy]$ ]]; then
            log_info "安装Certbot..."
            sudo apt install -y certbot python3-certbot-nginx
            
            log_info "获取SSL证书..."
            if sudo certbot --nginx -d $DOMAIN --non-interactive --agree-tos --email admin@$DOMAIN; then
                log_success "SSL证书配置成功"
                
                # 设置自动续期
                (crontab -l 2>/dev/null; echo "0 12 * * * /usr/bin/certbot renew --quiet") | crontab -
                log_info "SSL证书自动续期已配置"
            else
                log_warning "SSL证书配置失败，将继续使用HTTP"
            fi
        fi
    else
        log_info "使用IP地址，跳过SSL配置"
    fi
}

# 创建Nginx日志轮转配置
setup_log_rotation() {
    log_info "配置Nginx日志轮转..."
    
    sudo tee /etc/logrotate.d/nginx-memebot > /dev/null << EOF
/var/log/nginx/memebot_*.log {
    daily
    missingok
    rotate 30
    compress
    delaycompress
    notifempty
    create 644 www-data www-data
    postrotate
        if [ -f /var/run/nginx.pid ]; then
            kill -USR1 \$(cat /var/run/nginx.pid)
        fi
    endscript
}
EOF
    
    log_success "Nginx日志轮转配置完成"
}

# 主函数
main() {
    create_nginx_config
    enable_site
    test_nginx_config
    restart_nginx
    setup_log_rotation
    setup_ssl
    
    log_success "Nginx配置完成！"
    log_info "访问地址: http://$DOMAIN"
    if [ "$DOMAIN" != "$SERVER_IP" ]; then
        log_info "如果配置了SSL: https://$DOMAIN"
    fi
}

# 运行主函数
main "$@"
